package cn.signalpha.modules.com.controller.api;

import cn.signalpha.common.cache.ParamCache;
import cn.signalpha.common.cache.ParamKeys;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.dto.IdDTO;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.sms.model.SmsCode;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.base.dto.NoticeDTO;
import cn.signalpha.modules.base.entity.enums.NoticeTypeEnum;
import cn.signalpha.modules.com.dto.UserDTO;
import cn.signalpha.modules.com.entity.User;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.com.vo.UserVO;
import cn.signalpha.modules.com.wrapper.UserWrapper;
import cn.signalpha.modules.queue.enums.RedisDelayQueueEnum;
import cn.signalpha.modules.queue.utils.RedisDelayQueueUtil;
import cn.signalpha.modules.resource.builder.sms.SmsBuilder;
import cn.signalpha.modules.resource.utils.SmsUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Date;

/**
 * 控制器
 *
 * @author signalpha
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_USER_NAME + "/wap/user")
@Api(value = "用户", tags = "用户")
public class ApiUserController extends BaseController {

	private final SmsBuilder smsBuilder;
	private final UserService userService;
	private final RedisDelayQueueUtil redisDelayQueueUtil;

	@GetMapping("/info")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "用户信息", notes = "")
	public R<UserVO> info() {
		User user = userService.getById(getUser().getUserId());
		return R.data(UserWrapper.build().entityVO(user));
	}

	@GetMapping("/share/url")
	@ApiOperation(value = "分享链接", notes = "H5、APP用")
	public R shareUrl(TokenUser tokenUser) {
		return R.data(ParamCache.getValue(ParamKeys.URL_REGISTER) + tokenUser.getAccount());
	}

	@PostMapping("/update/mobile")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "绑定手机号", notes = "小程序、公众号用")
	public R updateMobile(@Valid @RequestBody UserDTO.UpdateMobileDTO mobileDTO) {
		User user = userService.getById(getUser().getUserId());
		Assert.isTrue(StringUtil.isBlank(user.getMobile()), "请不要重复绑定手机号");
		if(userService.countByMobile(mobileDTO.getMobile())){
			throw new ServiceException("该手机号已被使用");
		}
		if(StringUtil.isNotBlank(mobileDTO.getSmsCode())){
			Assert.isTrue(smsBuilder.template().validateMessage(new SmsCode().setPhone(mobileDTO.getMobile()).setValue(mobileDTO.getSmsCode())), SmsUtil.VALIDATE_FAIL);
		}
		userService.removeBaseById(user.getId());
		mobileDTO.setId(user.getId());
		return R.status(userService.updateById(BeanUtil.copy(mobileDTO, User.class)));
	}

	@PostMapping("/update/base")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "更新基础信息", notes = "")
	public R updateBase(@Valid @RequestBody UserDTO.UpdateBaseDTO updateBaseDTO) {
		updateBaseDTO.setId(getUser().getUserId());
		userService.removeBaseById(updateBaseDTO.getId());
		return R.status(userService.updateById(BeanUtil.copy(updateBaseDTO, User.class)));
	}

	@PostMapping("/update/parent")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "更新推荐人", notes = "二维码的id传回来")
	public void updatePid(@Valid @RequestBody IdDTO idDTO) {
		User userParent = userService.getById(Long.valueOf(idDTO.getId()));
		if(ObjectUtil.isNotEmpty(userParent) && userParent.getIsPlace() == 1){
			User user = userService.getById(getUser().getUserId());

			if(ObjectUtil.isEmpty(user.getParentId()) || user.getParentId() == 0){
				if(!userParent.getId().equals(user.getId())){
					//当前用户不能是推荐人的下级
					if(!Func.toLongList(userParent.getChain()).contains(user.getId())){
						userService.updateParentId(Collections.singletonList(user.getId()), Long.valueOf(idDTO.getId()));
						userService.updateById(User.builder().id(user.getId()).bindingTime(new Date()).build());
						userService.removeBaseById(user.getId());

						//推送消息
						NoticeDTO noticeDTO = new NoticeDTO();
						noticeDTO.setTargetId(user.getId());
						noticeDTO.setType(NoticeTypeEnum.USER_BINDING.getType());
						redisDelayQueueUtil.addDelayQueue(noticeDTO, 1, RedisDelayQueueEnum.NOTICE.getCode());
					}
				}
			}
		}
	}

}

